package com.ittx.dzt.shein.handler;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.ittx.dzt.business.PlatformConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.handler.AbstractBasePlatformApiHandler;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.mq.core.queue.producer.RocketmqProducer;
import com.ittx.dzt.okhttp.core.HttpRequestTemplate;
import com.ittx.dzt.shein.util.SheinSignUtil;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.SpringUtil;
import com.ittx.dzt.sys.util.json.JacksonTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 希音平台API处理父类
 * <p>
 *
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/8/1
 */
@Slf4j
public abstract class AbstractBaseSheinSemiApiHandler<T> extends AbstractBasePlatformApiHandler<T> {

	@Autowired
	protected RocketmqProducer rocketmqProducer;
	// 取值字段
	public static final String DATA_FIELD = "info";
	/**
	 * 查询总数
	 */
	public static final String RESULT_TOTAL = "count";

	@Override
	public String getPlatformCode() {
		return PlatformConstant.SHEIN_SEMI;
	}
	/**
	 * 时间类型转换
	 */
	public String localDateTimeToString(LocalDateTime localDateTime) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		return df.format(localDateTime);
	}

	/**
	 * 执行API请求通用方法
	 *
	 * @param storeConfig 店铺配置
	 * @param paramMap    请求参数
	 * @param requestId   请求id
	 * @return 请求结果
	 */
	public Result<?> executeApi(StoreConfigDTO storeConfig, Map<String, Object> paramMap, String requestId) {
		// 序列化参数
		String paramJson = JacksonTool.toJson(paramMap);
		// 发起请求
		Result result = null;
		try {
			result = fetch(storeConfig, paramJson, requestId);
			if (result.isSuccess()) {
				Map<String, Object> resultMap = JacksonTool.toMap(result.getData());
				String code = MapUtil.getStr(resultMap, "code");
				if (!"0".equals(code)) {
					String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getSheinSemiMethod(), result.getData());
					log.error(msg);
					return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(MapUtil.getStr(resultMap, "msg"));
				}
				return Result.success().addData(resultMap);
			}
			return result;
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getSheinSemiMethod(), e.getMessage());
			ExceptionLog.error(e, PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getSheinSemiMethod(), e.getMessage());
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(msg);
		}
	}

	/**
	 * 公共HTTP请求平台API
	 *
	 * @param storeConfig 店铺配置
	 * @param paramJson   请求参数
	 * @return 请求结果
	 * @throws IOException
	 */
	private Result<?> fetch(StoreConfigDTO storeConfig, String paramJson, String requestId)  {
		try {
			String url = storeConfig.getSdkUrl() + this.getSheinSemiMethod();
			HttpRequestTemplate httpRequestTemplate = SpringUtil.getBean(HttpRequestTemplate.class);
			if (httpRequestTemplate == null) {
				String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0006_MSG, HttpRequestTemplate.class.getName());
				log.error(msg);
				return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0006, msg));
			}
			String sessionKey = storeConfig.getSessionKey();
			if (StrUtil.isEmpty(sessionKey)) {
				return Result.error("授权信息为空");
			}
			String[] split = sessionKey.split("~-~");
			if (split.length != 2) {
				return Result.error(StrUtil.format("店铺授权信息token不合法:{}", sessionKey));
			}
			Map<String, String> headerMap = Maps.newHashMap();
			headerMap.put("Content-Type", ContentType.JSON.getValue());
			headerMap.put("x-lt-openKeyId", split[0]);
			headerMap.put("x-lt-timestamp", String.valueOf(System.currentTimeMillis()));
			headerMap.put("x-lt-signature", SheinSignUtil.generateSheinSignature(split[0], split[1], this.getSheinSemiMethod()));

			log.debug("url:{},headerMap:{}, reqMap:{}", url, JacksonTool.toJson(headerMap), paramJson);
			String returnMsg = httpRequestTemplate.postJsonParamsHeader(url, paramJson, headerMap);
			if (StrUtil.isEmpty(returnMsg) || !JSONUtil.isTypeJSON(returnMsg)) {
				String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0012_MSG, requestId, this.getPlatformCode()
						, this.getSheinSemiMethod(), url, returnMsg);
				log.error(msg);
				return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0012, msg));
			}
			return Result.success().addData(returnMsg);
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getSheinSemiMethod(), e.getMessage());
			ExceptionLog.error(e, PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getSheinSemiMethod(), e.getMessage());
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(msg);
		}
	}

	/**
	 * 获取抖音平台方法名称
	 *
	 * @return 抖音平台API
	 * @date 2022/5/5 15:01
	 */
	public abstract String getSheinSemiMethod();

	/**
	 * 获取总页数
	 *
	 * @param totalCount 总记录数
	 * @param pageSize   每页显示记录数
	 * @return 总页数
	 */
	public Integer totalPage(Integer totalCount, Integer pageSize) {
		if (totalCount <= pageSize) {
			return 1;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	public Long totalPage(Long totalCount, Long pageSize) {
		if (totalCount <= pageSize) {
			return 1L;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	/**
	 * 时间格式转换
	 */
	public String timeToString(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format).withZone(ZoneOffset.UTC);
		return df.format(localDateTime);
	}

	public String format(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
		return df.format(localDateTime);
	}
}
